import './WeChatBind.scss'
import { v4 } from 'uuid'
import { useState } from 'react'
import { useMount } from 'ahooks'
import { useRequest } from 'alova/client'
import { App, Result, Button } from "antd"

import { Http, API_LIST } from '../../Utils/Api'
import { WeChatConfig } from '../../Config/theme'
import { GetIndexedDB, PutIndexedDB } from '../../Utils/IndexedDB'

const { appid, redirect_uri } = WeChatConfig

const WeChatBind = ({ Off }) => {
    const { notification } = App.useApp()
    const [uuid] = useState(v4())
    const [status, setStatus] = useState(false)
    const [loading, setLoading] = useState(false)
    const [unionId, setUnionId] = useState()

    useMount(async () => {
        const { unionId } = await GetIndexedDB('user')
        if (!unionId) onBindFunc()
        setUnionId(unionId)
        setStatus(true)
    })

    const { send } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    const onBindFunc = () => {
        const state = `${uuid}@${appid}@jiantou`
        const get = `${API_LIST()['getUsersGetOpenUnionidOrTokenSSE']}?QRUuid=${uuid}&Type=unionid`
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid,
            scope: 'snsapi_login',
            response_type: 'code',
            redirect_uri: window.encodeURI(redirect_uri),
            state: state,
            style: 'black',
            href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
        }
        var eventSource = new EventSource(get)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => {
            const { data } = e
            if (data !== '0') {
                send({ url: 'posUsersBindOpenWeChatUnionIdAndUserId', params: { unionid: data } }).then(async () => {
                    const user = await GetIndexedDB('user')
                    user.unionId = data
                    await PutIndexedDB('user', user)
                    notification.success({ key: 'fromModify', message: '操作成功', description: '微信信息绑定成功!' })
                    eventSource.close()
                    Off()
                })
            }
        }
        eventSource.onerror = () => eventSource.close()
    }

    const onUnBind = () => {
        setLoading(true)
        send({ url: 'posUsersUnBindOpenWeChatUnionId' }).then(async () => {
            const user = await GetIndexedDB('user')
            user.unionId = ''
            await PutIndexedDB('user', user)
            notification.success({ key: 'fromModify', message: '操作成功', description: '微信绑定关系已解除!' })
            Off()
        })
    }

    return (
        <div className='WeChatBind'>
            {status &&
                <>
                    {!unionId ?
                        <div id="QRcode" /> :
                        <Result
                            status="warning"
                            title="是否要解除微信与用户的绑定?"
                            extra={[
                                <Button key="close" onClick={Off} loading={loading}>取消</Button>,
                                <Button key="submit" type="primary" danger onClick={onUnBind} loading={loading}>解除绑定</Button>
                            ]}
                        />
                    }
                </>
            }
        </div>
    );
};

export default WeChatBind;